package com.kfm.am;

import java.util.ArrayList;
import java.util.Comparator;

public class Demo {

    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();
        arrayList.add(new Student("zcj",22));
        arrayList.add(new Student("gbq",21));
        arrayList.add(new Student("gzy",19));
        arrayList.add(new Student("sps",20));
        // 匿名类
        arrayList.sort(new Comparator() {
            // 为了告诉 sort 方法 你使用我这个对象的什么属性进行排序
            @Override
            public int compare(Object o1, Object o2) {
                // 向下转型
                Student stu1 = (Student) o1;
                Student stu2 = (Student) o2;
                int result = stu1.getName().compareTo(stu2.getName());
                return result;
            }
        });
        sort(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
//                 向下转型
                Student stu1 = (Student) o1;
                Student stu2 = (Student) o2;
                int result = stu1.getName().compareTo(stu2.getName());
                return result;
            }
        }, arrayList);

        arrayList.forEach(obj -> System.out.println(obj));
    }

    public static void sort(ArrayList arrayList) {
        for (int i = 0; i < arrayList.size() - 1; i++) {
            for (int j = 0; j < arrayList.size() - i - 1; j++) {
                Student s1 = (Student)arrayList.get(j);
                Student s2 = (Student)arrayList.get(j + 1);
                if (s1.getName().compareTo(s2.getName()) > 0) {
                    // 交换位置
//                    a[j +1] = s1
                    arrayList.set(j + 1, s1);
                    arrayList.set(j, s2);
                }
            }
        }
    }

    public static void sort(Comparator comparator, ArrayList arrayList) {
        for (int i = 0; i < arrayList.size() - 1; i++) {
            for (int j = 0; j < arrayList.size() - i - 1; j++) {
                if (comparator.compare(arrayList.get(j), arrayList.get(j + 1)) > 0) {
                    Object temp = arrayList.set(j + 1, arrayList.get(j));
                    arrayList.set(j, temp);
                }
            }
        }
    }
}
